<?php
class form_fieldModel extends baseModel{
    protected $table = 'form_field';

    //字段列表
    public function field_list_data($fid)
    {
        return $this->select('fid='.$fid,'','sequence asc,id asc');
    }

    //字段列表
    public function field_list($fid)
    {
        $list=$this->field_list_data($fid);
        if(empty($list)){
            return;
        }
        foreach ($list as $key => $vo) {
            $data[$key]=$vo;
            $data[$key]['type_name']=api('expand_model','field_type',array('id'=>$vo['type'],'name'=>true));
        }
        return $data;
    }

    //获取字段信息
    public function field_info($field,$fid,$id=null) {
        $where='field="'.$field.'"';
        $where.=' AND fid='.$fid;
        if(!empty($id)){
        $where.=' AND id<>'.$id;
        }
        return $this->find($where);
    }

    //获取字段信息通过ID
    public function field_info_id($id) {
        $where['id']=$id;
        return $this->find($where);
    }


    public function field_add($data) {
        $form=model('form')->info($data['fid']);
        $data=api('expand_model','field_data',$data);
        //添加真实字段
         $sql="
        ALTER TABLE {$this->model->pre}form_data_{$form['table']} ADD {$data['field']} {$data['fild_name']}({$data['len']}{$data['decimal']}) DEFAULT NULL
        ";
        $this->model->query($sql);
        return $this->insert($data);
    }

    public function field_edit($data) {
        $info=$this->field_info_id($data['id']);
        $form=model('form')->info($data['fid']);
        $data=api('expand_model','field_data',$data);
        //添加真实字段
        $sql="
        ALTER TABLE {$this->model->pre}form_data_{$form['table']} CHANGE {$info['field']} {$data['field']} {$data['fild_name']}({$data['len']}{$data['decimal']})
        ";
        $this->model->query($sql);
        $condition['id']=intval($data['id']);
        return $this->update($condition,$data); 
    }

    //字段删除
    public function field_del($data)
    {
        $form=model('form')->info($data['fid']);
        $info=$this->field_info_id($data['id']);
        $sql="
             ALTER TABLE {$this->model->pre}form_data_{$form['table']} DROP {$info['field']}
            ";
        $this->model->query($sql);
        $condition['id']=intval($info['id']);
        return $this->delete($condition);
    }

    //通过表单删除
    public function form_del($fid)
    {
        $condition['fid']=intval($info['fid']);
        return $this->delete($condition);
    }
    
}

?>